package com.open.cloud.datasource.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.open.cloud.datasource.properties.MybatisPlusProperties;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 *
 * mybatis plus 元数据对象处理器
 * @author kong
 * @date 2021/2/12
 * blog: http://blog.kongyin.ltd
 */
public abstract class AbstractBaseMetaObjectHandler implements MetaObjectHandler {

    private MybatisPlusProperties mybatisPlusProperties;

    public AbstractBaseMetaObjectHandler(MybatisPlusProperties mybatisPlusProperties) {
        this.mybatisPlusProperties = mybatisPlusProperties;
    }

    @Override
    public boolean openInsertFill() {
        return mybatisPlusProperties.getEnableInsertFill();
    }

    @Override
    public boolean openUpdateFill() {
        return mybatisPlusProperties.getEnableUpdateFill();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        String operatorId = getOperatorId();
        Object createBy = getFieldValByName(mybatisPlusProperties.getCreateByField(), metaObject);
        Object updateBy = getFieldValByName(mybatisPlusProperties.getUpdateByField(), metaObject);
        Object createTime = getFieldValByName(mybatisPlusProperties.getCreateTimeField(), metaObject);
        Object updateTime = getFieldValByName(mybatisPlusProperties.getUpdateTimeField(), metaObject);
        if (createTime == null) {
            setFieldValByName(mybatisPlusProperties.getCreateTimeField(), new Date(), metaObject);
        }
        if (updateTime == null) {
            setFieldValByName(mybatisPlusProperties.getUpdateTimeField(), new Date(), metaObject);
        }
        if (createBy == null) {
            setFieldValByName(mybatisPlusProperties.getCreateByField(), operatorId, metaObject);
        }
        if (updateBy == null) {
            setFieldValByName(mybatisPlusProperties.getUpdateByField(), operatorId, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String operatorId = getOperatorId();
        this.setFieldValByName(mybatisPlusProperties.getUpdateTimeField(), new Date(), metaObject);
        this.setFieldValByName(mybatisPlusProperties.getUpdateByField(), operatorId, metaObject);
    }

    /**
     * 获取当前操作人id
     *
     * @return 操作人id
     */
    public abstract String getOperatorId();
}
